﻿using RpcCentral.Collect;
using RpcCentral.Collect.Controller;
using RpcCentral.Common;
using RpcCentral.Model;
using RpcCentral.Service.Interface;
using WeDonekRpc.Model;

namespace RpcCentral.Service.Service
{
    internal class GetServerNodeService : IGetServerNodeService
    {
        private readonly IRpcTokenCollect _TokenCollect;
        private readonly IRpcServerCollect _Server;
        private readonly IServerClientLimitCollect _ClientLimit;
        private readonly IRpcServerStateCollect _RunState;
        private readonly IReduceInRankCollect _ReduceInRank;
        public GetServerNodeService (IRpcTokenCollect token,
            IRpcServerCollect server,
            IReduceInRankCollect reduceInRank,
            IRpcServerStateCollect runState,
            IServerClientLimitCollect clientLimit)
        {
            this._RunState = runState;
            this._ReduceInRank = reduceInRank;
            this._ClientLimit = clientLimit;
            this._Server = server;
            this._TokenCollect = token;
        }
        public ServerConfigInfo Get (GetRemoteServer obj)
        {
            _ = this._TokenCollect.Get(obj.AccessToken);
            RpcServerController rpcServer = this._Server.GetRpcServer(obj.ServerId);
            RemoteServerModel datum = rpcServer.Server;
            ServerConfigInfo server = datum.ConvertMap<RemoteServerModel, ServerConfigInfo>();
            server.Name = datum.ServerName;
            server.ServerId = rpcServer.ServerId;
            server.Reduce = this._ReduceInRank.GetReduceInRank(datum.HoldRpcMerId, rpcServer.ServerId);
            server.ClientLimit = this._ClientLimit.GetClientLimit(datum.HoldRpcMerId, rpcServer.ServerId);
            server.IsEnablePipe = this._CheckIsEnablePipe(rpcServer, obj.Environment);
            if (datum.RegionId != obj.RegionId)
            {
                server.ServerIp = datum.RemoteIp;
                server.ServerPort = datum.RemotePort;
            }
            server.GroupTypeVal = rpcServer.GroupTypeVal;
            return server;
        }
        private bool _CheckIsEnablePipe (RpcServerController server, LocalEnvironment env)
        {
            if (!server.Server.IsEnablePipe || server.Server.ServerMac != env.Mac)
            {
                return false;
            }
            RunEnvironment conEnv = this._RunState.GetEnvironments(server.ServerId);
            if (conEnv == null)
            {
                return false;
            }
            return env.RunUserIdentity == conEnv.RunUserIdentity && env.RunIsAdmin == conEnv.RunIsAdmin;
        }
    }
}
